package com.sam.generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenericTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		List<String> strings = new ArrayList<String>();

		unsafeAdd(strings, 2);
		//String s = strings.get(0);
		safeAdd(strings, "");

		List<Integer> list = new ArrayList<Integer>();

		add(list);
		
		
		Favorite favorite=new Favorite();
		
		favorite.put(String.class, "12345");
		//favorite.put2(String.class,1);
		
		favorite.get(String.class);
		

	}

	/**
	 * 不安全添加方法类型错误编译时无法检查出
	 * 
	 * @param list
	 * @param object
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static void unsafeAdd(List list, Object object) {

		list.add(object);

	}

	/**
	 * 安全添加
	 * 
	 * @param list
	 * @param object
	 */
	private static void safeAdd(List<String> list, String object) {

		list.add(object);

	}

	public static void add(List<? extends Number> list) {

	}

	/**
	 * 泛型异构
	 * 
	 * @author Administrator
	 * 
	 */
	public static class Favorite {

		private final Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();

		public <T> void put(Class<T> type, T instance) {

			if (instance == null) {
				throw new NullPointerException("instance is null!");
			}

			this.map.put(type, instance);

		}

		public void put2(Class<?> type, Object instance) {
			if (instance == null) {
				throw new NullPointerException("instance is null!");
			}

			this.map.put(type, instance);

		}

		public <T> T get(Class<T> type) {

			return type.cast(this.map.get(type));

		}

	}

}
